package com.example.pixelyear.utils.oss;

import android.content.Context;

import com.alibaba.sdk.android.oss.*;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCustomSignerCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.*;
import com.example.pixelyear.Interface.OnOssBackUpListener;
import com.example.pixelyear.Interface.OnOssDownloadListener;
import com.example.pixelyear.Interface.OnOssRestoreListener;
import com.socks.library.KLog;

import java.io.InputStream;

public class NetBackBackUpUtils {
    private OSSCustomSignerCredentialProvider credentialProvider = new OSSCustomSignerCredentialProvider() {
        @Override
        public String signContent(String content) {
            // 按照OSS规定的签名算法加签字符串，并将得到的加签字符串拼接AccessKeyId后返回。
            // 将加签的字符串传给您的服务器，然后返回签名。如果因某种原因加签失败，服务器描述错误信息后返回null。
            return OSSUtils.sign(Config.OSS_ACCESS_KEY_ID, Config.OSS_ACCESS_KEY_SECRET, content);
        }
    };
    private OSS oss;
    //    String stsServer = "STS应用服务器地址，例如http://abc.com";
    private static NetBackBackUpUtils mInstance;

    public static NetBackBackUpUtils getInstance(Context context) {
        if (mInstance == null) {
            synchronized (NetBackBackUpUtils.class) {
                if (mInstance == null) {
                    mInstance = new NetBackBackUpUtils(context);
                }
            }
        }
        return mInstance;
    }


    private NetBackBackUpUtils(Context context) {
        init(context);
    }

    private void init(Context context) {
        // 推荐使用OSSAuthCredentialsProvider。token过期可以及时更新。

        // 配置类如果不设置，会有默认配置。
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒。
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒。
        conf.setMaxConcurrentRequest(5); // 最大并发请求数，默认5个。
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次。

        oss = new OSSClient(context.getApplicationContext(), Config.OSS_ENDPOINT, credentialProvider);
    }


    public void createSpace() {
        CreateBucketRequest createBucketRequest = new CreateBucketRequest("shuai-back-up");
        // 设置存储空间的访问权限为公共读，默认为私有读写。
        createBucketRequest.setBucketACL(CannedAccessControlList.PublicRead);
        // 指定存储空间所在的地域。
        createBucketRequest.setLocationConstraint("oss-cn-hangzhou");
        OSSAsyncTask createTask = oss.asyncCreateBucket(createBucketRequest, new OSSCompletedCallback<CreateBucketRequest, CreateBucketResult>() {
            @Override
            public void onSuccess(CreateBucketRequest request, CreateBucketResult result) {
                KLog.e("yxs", "locationConstraint：" + request.getLocationConstraint());
            }

            @Override
            public void onFailure(CreateBucketRequest request, ClientException clientException, ServiceException serviceException) {
                // 请求异常。
                if (clientException != null) {
                    // 本地异常，如网络异常等。
                    clientException.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常。
                    KLog.e("yxs", "ErrorCode：" + serviceException.getErrorCode());
                    KLog.e("yxs", "RequestId：" + serviceException.getRequestId());
                    KLog.e("yxs", "HostId：" + serviceException.getHostId());
                    KLog.e("yxs", "RawMessage：" + serviceException.getRawMessage());
                }
            }
        });
    }

    public boolean checkFileExists(String name) {
        try {
            return oss.doesObjectExist(Config.BUCKET_NAME, name);
        } catch (ClientException e) {
            // 本地异常如网络异常等
            e.printStackTrace();
        } catch (ServiceException e) {
            // 服务异常
            KLog.e("ErrorCode", e.getErrorCode());
            KLog.e("RequestId", e.getRequestId());
            KLog.e("HostId", e.getHostId());
            KLog.e("RawMessage", e.getRawMessage());
        }
        return false;
    }


    public void backUp(final String name, String path, final OnOssBackUpListener listener) {
        // 构造上传请求。
        PutObjectRequest put = new PutObjectRequest(Config.BUCKET_NAME, name, path);

        oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                if (listener != null)
                    listener.onSuccess();
                KLog.e("yxs", "上传成功：" + name);
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常。
                if (clientExcepion != null) {
                    // 本地异常，如网络异常等。
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常。
                    KLog.e("yxs", "ErrorCode：" + serviceException.getErrorCode());
                    KLog.e("yxs", "RequestId：" + serviceException.getRequestId());
                    KLog.e("yxs", "HostId：" + serviceException.getHostId());
                    KLog.e("yxs", "RawMessage：" + serviceException.getRawMessage());
                }
                if (listener != null)
                    listener.onFailure();
            }
        });
    }

    public void restore(String name, final OnOssRestoreListener listener) {
        GetObjectRequest get = new GetObjectRequest(Config.BUCKET_NAME, name);
        oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
            @Override
            public void onSuccess(GetObjectRequest request, GetObjectResult result) {
                // 请求成功
                if (listener != null)
                    listener.onSuccess(result.getObjectContent());

            }

            @Override
            public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    KLog.e("yxs", "ErrorCode：" + serviceException.getErrorCode());
                    KLog.e("yxs", "RequestId：" + serviceException.getRequestId());
                    KLog.e("yxs", "HostId：" + serviceException.getHostId());
                    KLog.e("yxs", "RawMessage：" + serviceException.getRawMessage());
                }
                if (listener != null)
                    listener.onFailure();
            }
        });
    }

    public OSSAsyncTask<GetObjectResult> download(String name, final OnOssDownloadListener listener) {
        GetObjectRequest get = new GetObjectRequest(Config.BUCKET_NAME, name);
        //设置下载进度回调
        get.setProgressListener(new OSSProgressCallback<GetObjectRequest>() {
            @Override
            public void onProgress(GetObjectRequest request, long currentSize, long totalSize) {
                if (listener != null)
                    listener.progress(totalSize, currentSize);
            }
        });
        return oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
            @Override
            public void onSuccess(GetObjectRequest request, GetObjectResult result) {
                // 请求成功
                if (listener != null)
                    listener.onSuccess(result.getObjectContent());

            }

            @Override
            public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    KLog.e("yxs", "ErrorCode：" + serviceException.getErrorCode());
                    KLog.e("yxs", "RequestId：" + serviceException.getRequestId());
                    KLog.e("yxs", "HostId：" + serviceException.getHostId());
                    KLog.e("yxs", "RawMessage：" + serviceException.getRawMessage());
                }
                if (listener != null)
                    listener.onFailure();
            }
        });
    }

}
